from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views import View
import requests
import hashlib
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
from mydjango.settings import UPLOAD_ROOT, BASE_DIR
from userapp.models import User, Course, Coupons
from .myser import OrderSer, Comment1Ser
from userapp.ser import UserSer, CouponsSer
from mydjango.myser import Course_CommentSer
# 导入原生sql模块
from django.db import connection
import os
from django.shortcuts import render, HttpResponse  # 引入HttpResponse
from dwebsocket.decorators import accept_websocket  # 引入dwbsocket的accept_websocket装饰器
from alipay import AliPay
# 如果没有alipay，就执行PIP INSTALL python-alipay-sdk --upgrade
from courseapp.models import Orders, Course_Comment
# 导入uuid
import uuid
# 导入随机数包
import random
import string
# 导入时间模块
from datetime import datetime

# 支付宝初始化 设置支付宝公私钥
# 用户的私钥
app_private_key_string = open(os.path.join(BASE_DIR, "static/utils/app_private_2048.txt")).read()
# 支付宝公钥
alipay_public_key_string = open(os.path.join(BASE_DIR, "static/utils/ailipay_public_2048.txt")).read()


class MyView(View):
    def get(self, request):
        return HttpResponse("Hello world !")


# 初始化阿里支付对象
def get_ali_object():
    app_id = '2016102200739381'  # APPID （沙箱应用）
    # 回调网址  支付完成后，跳转的地址。
    return_url = 'http://localhost:8000/ali_back/'
    # 实例化对象
    alipay = AliPay(
        appid=app_id,
        app_notify_url=return_url,
        # 私钥地址
        app_private_key_string=app_private_key_string,
        # alipay public key, do not use your own public key!
        alipay_public_key_string=alipay_public_key_string,
        debug=True  # False by default.如果是沙箱环境。配置为True
    )
    return alipay


class Order_info(View):
    def get(self, request):
        uid = request.GET.get('id')
        # 建立游标对象
        cursor = connection.cursor()
        # 执行sql语句
        cursor.execute(
            'select a.order_id,a.course_id,a.price,a.is_complete,a.creat_time,a.type,b.username,b.img from orders as a inner join user as b on a.uid = b.id where b.id= ' + str(
                uid)
        )
        # 获取结果
        # result = cursor.fetchall()
        result = dictfetchall(cursor)
        # 返回结果 手动序列化
        return HttpResponse(json.dumps(result, ensure_ascii=False, indent=4, default=str),
                            content_type='application/json')

        # # print(uid)
        # orders = Orders.objects.filter(uid=uid)
        # order_list = OrderSer(orders, many=True).data
        # user = User.objects.filter(id=uid).first()
        # userinfo = UserSer(user).data
        # return Response({'code': 200, 'order_list': order_list, 'userinfo': userinfo})


# 对结果集美化方法
def dictfetchall(cursor):
    # 获取游标描述
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]


class Order_course(View):
    def get(self, request):
        # 建立游标对象
        cursor = connection.cursor()
        # 执行sql语句
        cursor.execute(
            'select s.title,s.id from course as s inner join orders as c on s.id = c.course_id '
        )
        # 获取结果
        # result = cursor.fetchall()
        result = dictfetchall(cursor)
        # 返回结果 手动序列化
        return HttpResponse(json.dumps(result, ensure_ascii=False, indent=4, default=str),
                            content_type='application/json')


# 支付网址视图
class AilpayView(APIView):
    def get(self, request):
        price = request.GET.get('price')
        order_id = request.GET.get('order_id')
        # 获取实例
        alipay = get_ali_object()

        # 电脑网站支付，需要跳转到https: // openapi.alipay.com / gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 订单号
            total_amount=price,  # 支付金额
            subject='感谢您购买实验楼相关项目！',
            return_url='http://localhost:8080/payok/',
            notify_url=None  # 可选, 不填则使用默认notify url
        )

        # 拼接网址
        pay_url = "https://openapi.alipaydev.com/gateway.do?" + order_string  # 支付宝网关地址（沙箱应用）
        return HttpResponseRedirect(pay_url)


# 定义回调方法
class CheckOrder(APIView):
    def post(self, request):
        order_id = request.data.get('order_id')
        print("order_id", order_id)
        print(request.data)

        alipay = AliPay(
            appid="2016102200739381",
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True  # 默认False
        )
        resp = alipay.api_alipay_trade_query(order_id)
        print(resp)
        order = Orders.objects.filter(order_id=order_id).first()
        res = {}
        if resp["code"] == "10000":
            # 如果订单成功，修改 订单状态
            order.is_complete = 1  # 1代码支付成功
            order.save()
            res["code"] = 200
            res["msg"] = "支付成功"
        else:
            # order.status = 2  # 支付失败
            # order.save()
            res["code"] = 400
            res["msg"] = "支付失败,请联系管理员"
        return Response(res)


# 获取价格
class GetMemberPrice(APIView):
    def post(self, request):
        level = request.data.get('level', None)
        print(level)

        if level == "会员":
            res = {}
            res['code'] = 200
            res['amount'] = 699
            return Response(res)

        elif level == "高级会员":
            res = {}
            res['code'] = 200
            res['amount'] = 1299
            return Response(res)

        else:
            res = {}
            res['code'] = 405
            return Response(res)


# 订单信息入库
class MemberOrder(APIView):
    def post(self, request):
        code_s = string.ascii_letters + string.digits
        order_id = ''.join(random.sample(code_s, 10))

        # 获取前端传递参数
        user_id = request.data.get('user_id', None)
        course_id = request.data.get('cid', None)
        # course_id = request.data.get('course_id',0)
        price = request.data.get("price", None)
        type = request.data.get("type", '0')
        # print(type)

        # 将参数输出展示
        a_dict = {"user_id": user_id, 'price': price, 'type': type, 'course_id': course_id}
        print(a_dict)
        # 会员订单排重
        order = Orders.objects.filter(order_id=order_id).first()
        if order:
            res = {}
            res['code'] = 10010
            res['message'] = "您的订单已提交,请勿重复下单"

            return Response(res)
        else:
            if course_id is None:
                order = Orders(order_id=order_id, uid=int(user_id), price=int(price), is_complete=0,
                               creat_time=datetime, type=int(type))
                order.save()
            else:
                order = Orders(order_id=order_id, uid=int(user_id), price=int(price), is_complete=0,
                               creat_time=datetime, type=0, course_id=course_id)
                order.save()
            res = {}
            res['code'] = 200
            # res['order_sn'] = 'order_sn'
            res['price'] = price
            res['order_id'] = order_id
            res['message'] = "您的订单已提交成功,稍后将跳转到支付页面"

            return Response(res)


# 查看优惠券信息
class Show_Coupons(APIView):
    def get(self, request):
        coupons = Coupons.objects.filter()
        coupons_ser = CouponsSer(coupons, many=True)

        res = {}
        res['code'] = 200
        res['data'] = coupons_ser.data

        return Response(res)


# 无限极评论
def xTree(datas):
    lists = []
    tree = {}
    parent_id = ''
    for i in datas:
        item = i
        tree[item['id']] = item
    root = None
    for i in datas:
        obj = i
        if not obj['pid']:
            root = tree[obj['id']]
            lists.append(root)
        else:
            parent_id = obj['pid']
            if 'childlist' not in tree[parent_id]:
                tree[parent_id]['childlist'] = []
            tree[parent_id]['childlist'].append(tree[obj['id']])
    return lists


# 课程评论接口
class Comment(View):
    def get(self, request):
        id = request.GET.get('id')
        # 建立游标对象
        cursor = connection.cursor()
        # 执行sql语句
        cursor.execute(
            'select a.id,b.username,b.img,a.content,a.time,a.pid from course_comment as a inner join user as b on a.uid = b.id where a.course_id=1 order by a.time desc'
        )
        # 获取结果
        # result = cursor.fetchall()
        result = dictfetchall(cursor)
        mylist = xTree(result)
        # 返回结果 手动序列化
        return HttpResponse(json.dumps(mylist, ensure_ascii=False, indent=4, default=str),

                            content_type='application/json')


class CommentView(APIView):
    def post(self, request):
        comment_data = request.data
        print(comment_data)
        commser = Comment1Ser(data=comment_data)
        print(commser.is_valid())
        if commser.is_valid():
            commser.save()

        res = {}
        res['code'] = 200
        return Response(res)
